import time
import datetime

from flask import render_template, jsonify, current_app
from redis import Redis

from apps.online_tools import online_tools_bp
from celery_tasks.celery_test.tasks import function_haoshi


@online_tools_bp.route('/')
def index():
    return render_template('tests/celery_test.html')


@online_tools_bp.route('/haoshi')
def haoshi():
    """假装这是一个耗时任务"""
    # 获取当前时间的字符串
    current_time = datetime.datetime.now().strftime("%H:%M:%S")

    # # 耗时操作
    # redis_conn = Redis(**current_app.config['REDIS_CONFIG_1'])
    # time.sleep(10)
    # redis_conn.set('celery_test', current_time, 300)
    function_haoshi.delay(current_time)

    response = {
        "msg": f"10s秒后将当前时间“{current_time}”存入Redis"
    }
    return jsonify(response)


@online_tools_bp.route('/chaxun')
def chaxun():
    """查询Redis数据库"""
    redis_conn = Redis(**current_app.config['REDIS_CONFIG_1'])
    result = redis_conn.get('celery_test')
    if result:
        response = {
            "result": redis_conn.get('celery_test').decode()
        }
    else:
        response = {
            "result": None
        }
    return jsonify(response)
